<template>
    <div class="doc_manage_span">
        <table-span :current-page="tabelData.current" :page-size="tabelData.size" :total="tabelData.total"
            :isShowTool="false" :isShowPagePlug="false" :size-change="handleSizeChange"
            :current-change="handleCurrentChange">
            <template v-slot:searchItem>
                <div class="search_item_span search_item_input_width">
                    <el-input size="default" v-model="searchCondition.title" placeholder="请输入标题" clearable></el-input>
                </div>
                <div class="search_item_span">
                    <el-button icon="Search" size="default" type="primary" @click="searchData">查询</el-button>
                </div>
                <div class="search_item_span">
                    <el-button icon="Plus" size="default" type="primary" :disabled="!(btOption.btDocInfoSave)"
                        @click="openDocInfoDialog">新增文档</el-button>
                </div>
            </template>
            <template v-slot:searchTable>
                <el-table :data="docList" size="default" height="100%" style="width: 100%;">
                    <el-table-column align="center" type="index" width="50">
                    </el-table-column>
                    <el-table-column align="center" prop="title" label="标题" min-width="260">
                    </el-table-column>
                    <el-table-column align="center" prop="shareActivityName" label="分享期限" width="120">
                    </el-table-column>
                    <el-table-column align="center" prop="shareTypeName" label="分享类型" width="120">
                    </el-table-column>
                    <el-table-column align="center" prop="expirationDate" label="到期时间" width="240">
                    </el-table-column>
                    <el-table-column fixed="right" align="center" label="操作" width="320">
                        <template #default="scope">
                            <el-button size="small" type="success"
                                @click="getShareMessage(scope.$index, scope.row)">分享码</el-button>
                            <el-button size="small" type="success"
                                @click="getDetail(scope.$index, scope.row)">详情</el-button>
                            <el-button size="small" :disabled="!(btOption.btDocInfoUpdate)"
                                @click="updateData(scope.$index, scope.row)">编辑</el-button>
                            <el-button size="small" type="danger" :disabled="!(btOption.btDocInfoDelete)"
                                @click="deleteData(scope.$index, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </template>
        </table-span>
        <el-dialog :title="docInfoOption.title" v-model="docInfoOption.isShow" @close="docInfoDialogClose"
            :before-close="docInfoDialogBeforeClose" :close-on-click-modal="false"
            :close-on-press-escape="false" width="420px">
            <el-form ref="docInfoFormRef" :model="docInfoForm" :rules="docInfoRules" label-width="80px" size="default">
                <el-form-item label="文档标题" prop="title">
                    <el-input v-model="docInfoForm.title" placeholder="请输入文档标题" :clearable="true" />
                </el-form-item>
                <el-form-item label="分享类型" prop="shareType">
                    <el-select v-model="docInfoForm.shareType"  placeholder="请选择分享类型" style="width:300px" @change="shareTypeChange">
                        <el-option
                        v-for="item in shareType"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item v-if="docInfoForm.shareType == 2">
                    <el-button size="default" @click="selectUser">选择人员</el-button>
                    <el-text type="info" style="margin-left: 10px;">已选择{{selectUserOption.result.length}}人</el-text>
                </el-form-item>
                <el-form-item label="分享期限" prop="shareActivity" v-if="docInfoForm.shareType == 1 || docInfoForm.shareType == 2">
                    <el-select v-model="docInfoForm.shareActivity"  placeholder="请选择分享期限" style="width:300px" @change="shareActivityChange">
                        <el-option
                        v-for="item in shareActivity"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="有效期限" prop="expirationDate" v-if="docInfoForm.shareActivity == 2">
                    <el-date-picker
                        v-model="docInfoForm.expirationDate"
                        type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请选择日期时间"
                        style="width:300px"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button size="default" @click="dialogCancel">取 消</el-button>
                <el-button size="default" type="primary" @click="dialogConfirm">确认</el-button>
            </template>
        </el-dialog>
        <el-dialog :title="docCreateOption.title" v-model="docCreateOption.isShow" :fullscreen="true"
        :close-on-click-modal="false" :close-on-press-escape="false" class="doc_create_dialog" 
        :destroy-on-close="true"
        :before-close="createDocDialogBeforeClose"
        @close="createDocDialogClose">
            <doc-create ref="docCreateRef" :docData="docCreateOption.selectDocData" :authority="btOption"></doc-create>
        </el-dialog>
        <el-dialog title="分享信息" v-model="shareMessage.isShowShareMessage"
        :close-on-click-modal="false" :close-on-press-escape="false"  
        destroy-on-close width="320px">
            <div class="qr_span">
                <qrcode-vue :value="shareMessage.url" :size="200" level="H"></qrcode-vue>
            </div>
            <el-input v-model="shareMessage.url" placeholder="" style="margin-top: 10px;" :readonly="true">
                <template #append>
                    <el-link :underline="false" @click="copyUrl">复制</el-link>
                </template>
            </el-input>
        </el-dialog>
        <SelectUser :isShow="selectUserOption.isShow" 
        :result="selectUserOption.result"
        :closed="selectUserClosed"
        :confirm="selectUserConfirm"
        ></SelectUser>
    </div>
</template>
<script>
import TableSpan from '@/components/table-span.vue';
import { tool } from "@/js/tool.js";
import { ElMessage } from 'element-plus';
import DocCreate from '@/components/doc-create.vue';
import SelectUser from '@/components/select-user.vue';
import QrcodeVue from 'qrcode.vue';
import { config } from "@/js/config.js";

export default {
    name: "document",
    data: function () {
        return {
            btOption: {
                btDocInfoSave: null,
                btDocInfoUpdate: null,
                btDocInfoDelete: null,
                btChapterSave: null,
                btChapterUpdate: null,
                btChapterDelete: null,
                btSaveUpdateContent: null
            },
            tabelData: {
                total: 0,
                size: 10,
                current: 1,
                records: []
            },
            docList: null,
            searchCondition: {
                title: null,
                page: null,
                size: null
            },
            docInfoOption: {
                title: null,
                isShow: false,
                type: 0 //0新增；1更新
            },
            docInfoForm: {
                mainId: null,
                title: null,
                shareType: null,
                shareActivity: null,
                expirationDate: null,
                userIdList: [],
            },
            docInfoRules: {
                title: [
                    { required: true, message: '请填写标题', trigger: 'blur' }
                ],
                shareType: [
                    { required: true, message: '请选择分享类型', trigger: 'blur' }
                ],
                shareActivity: [
                    { required: true, message: '请选择分享期限', trigger: 'blur' }
                ],
                expirationDate: [
                    { required: true, message: '请选择到期时间', trigger: 'blur' }
                ]
            },
            shareType: [
                {value: 0, label: "私有"},
                {value: 1, label: "所有人"},
                {value: 2, label: "指定人员"}
            ],
            shareActivity: [
                {value: 0, label: "未生效"},
                {value: 1, label: "长期有效"},
                {value: 2, label: "指定时间"}
            ],
            docCreateOption: {
                isShow: false,
                selectDocData: null,
                title: null
            },
            shareMessage: {
                isShowShareMessage: false,
                url: ""
            },
            selectUserOption: {
                isShow: false,
                result: []
            }
        }
    },
    methods: {
        searchData: function () {
            getDocList(this);
        },
        handleSizeChange: function (size) {
            this.tabelData.size = size;
            this.tabelData.current = 1;
            getDocList(this);
        },
        handleCurrentChange: function (current) {
            this.tabelData.current = current;
            getDocList(this);
        },
        openDocInfoDialog: function () {
            this.docInfoOption.title = "新增文档";
            this.docInfoOption.type = 0;
            this.docInfoOption.isShow = true;
        },
        updateData: function (index, row) {
            this.docInfoOption.title = "更新文档";
            this.docInfoOption.type = 1;
            this.docInfoOption.isShow = true;
            this.docInfoForm.mainId = row.mainId;
            this.docInfoForm.title = row.title;
            this.docInfoForm.shareType = row.shareType;
            this.docInfoForm.shareActivity = row.shareActivity;
            if(this.docInfoForm.shareActivity == 2){
                this.docInfoForm.expirationDate = row.expirationDate;
            }
            if(this.docInfoForm.shareType == 2){
                //查询指定人员
                getShareUserList(this);
            }
        },
        deleteData: function (index, row) {
            let confirmMessage = "是否删除:"+ row.title +"？";
            const obj = this;
            this.$confirm(confirmMessage).then(function () {
                const param = {
                    mainId: row.mainId
                }
                deleteDocInfo(obj, param);
            }).catch(function () {});
        },
        getDetail: function(index, row) {
            this.docCreateOption.isShow = true;
            this.docCreateOption.selectDocData = row;
            this.docCreateOption.title = "文档详情-" + row.title;
        },
        docInfoDialogClose: function () {
            this.docInfoForm.mainId = null;
            this.docInfoForm.title = null;
            this.docInfoForm.shareType = null;
            this.docInfoForm.shareActivity = null;
            this.docInfoForm.expirationDate = null;
            this.docInfoForm.userIdList = [];
            this.$refs["docInfoFormRef"].clearValidate();

            this.selectUserOption.result = [];
        },
        docInfoDialogBeforeClose: function () {
            dialogCloseTips(this);
        },
        dialogConfirm: function(){
            const obj = this;
            this.$refs["docInfoFormRef"].validate(function(valid) {
                if(valid){
                    if(obj.docInfoForm.shareType == 2){
                        setSelectUserIdList(obj);
                    }
                    if(obj.docInfoOption.type == 0){
                        //新增
                        saveDocInfo(obj);
                    }else{
                        //更新
                        updateDocInfo(obj);
                    }
                }else{
                    return false;
                }
            });
        },
        dialogCancel: function(){
            dialogCloseTips(this);
        },
        shareTypeChange: function(val){
            if(val == 0){
                this.docInfoForm.shareActivity = 1;
                this.docInfoForm.expirationDate = null;
            }
        },
        shareActivityChange: function(val){
            if(val == 0 || val == 1){
                this.docInfoForm.expirationDate = null;
            }
        },
        createDocDialogBeforeClose: function(){
            var confirmMessage = "是否要退出章节内容的编辑？";
            var obj = this;
            this.$confirm(confirmMessage).then(function () {
                obj.docCreateOption.isShow = false;
            }).catch(function () { });
        },
        createDocDialogClose: function(){
            this.$refs.docCreateRef.removeEditor();
            this.$refs.docCreateRef.removeKeydown();
        },
        getShareMessage: function(index, row){
            this.shareMessage.isShowShareMessage = true;
            const shareUrl = config.domain + "/" + config.projectRootName+ "/doc/share?shareCode=" + row.shareCode;
            this.shareMessage.url = shareUrl;
        },
        copyUrl: function(){
            navigator.clipboard.writeText(this.shareMessage.url)
            .then(() => {
                ElMessage({
                    showClose: true,
                    message: '复制成功',
                    type: 'success'
                });
            })
            .catch(() => {
                ElMessage({
                    showClose: true,
                    message: '复制失败',
                    type: 'error'
                });
            });
        },
        selectUser: function(){
            this.selectUserOption.isShow = true;
        },
        selectUserClosed: function(){
            this.selectUserOption.isShow = false;
        },
        selectUserConfirm: function(){
            
        }
    },
    created: function () {
        const menuId = [this.$route.query.menuId]
        const obj = this;
        new tool.getAuthorisedRequest(menuId, this.btOption, function () {
            getDocList(obj);
        });
    },
    components: {
        TableSpan,
        DocCreate,
        QrcodeVue,
        SelectUser
    }
}

/**
 * 获取选择用户的Id列表
 */
function setSelectUserIdList(app){
    app.docInfoForm.userIdList = new Array();
    const userList = app.selectUserOption.result;
    for(let i=0;i<userList.length;i++){
        let item = userList[i];
        app.docInfoForm.userIdList.push(item.userId);
    }
}

/**
 * 获取文档信息列表
 */
function getDocList(app) {
    const param = app.searchCondition;
    app.searchCondition.page = app.tabelData.current;
    app.searchCondition.size = app.tabelData.size;
    const url = "/doc/info/list";
    tool.formJsonRequest(url, param, null, function (data) {
        if (data.code === "0000") {
            const result = data.data;
            app.docList = result.records;
            app.tabelData.total = result.total;
            app.tabelData.current = result.current;
            app.tabelData.size = result.size;
        } else {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 获取分享文档指定人员
 */
 function getShareUserList(app) {
    const param = {
        mainId: app.docInfoForm.mainId
    }
    const url = "/doc/info/detail";
    tool.formJsonRequest(url, param, null, function (data) {
        if (data.code === "0000") {
            const result = data.data;
            app.selectUserOption.result = result.userList;
        } else {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 保存文档信息
 */
function saveDocInfo(app){
    const param = app.docInfoForm;
    const url = "/doc/info/save";
    tool.formJsonRequest(url, param, null, function (data) {
        if (data.code === "0000") {
            getDocList(app);
            app.docInfoOption.isShow = false;
        } else {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 更新文档信息
 */
function updateDocInfo(app){
    const param = app.docInfoForm;
    const url = "/doc/info/update";
    tool.formJsonRequest(url, param, null, function (data) {
        if (data.code === "0000") {
            getDocList(app);
            app.docInfoOption.isShow = false;
        } else {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 删除文档信息
 */
function deleteDocInfo(app, param){
    const url = "/doc/info/delete";
    tool.formJsonRequest(url, param, null, function (data) {
        if (data.code === "0000") {
            getDocList(app);
        } else {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 关闭dialog的提示信息
 * @param app
 */
function dialogCloseTips(app) {
    var confirmMessage = "";
    if (app.docInfoOption.type == 0) {
        confirmMessage = "是否放弃新增文档信息？";
    } else {
        confirmMessage = "是否放弃修改文档信息？";
    }
    var obj = app;
    app.$confirm(confirmMessage).then(function () {
        obj.docInfoOption.isShow = false;
    }).catch(function () { });
}
</script>
<style>
.doc_manage_span {
    position: relative;
    display: flex;
    flex-direction: row;
    width: 100%;
    height: 100%;
    font-family: Microsoft YaHei, Heiti SC, tahoma, arial, Hiragino Sans GB, "\5B8B\4F53", sans-serif;
}

.search_item_span {
    max-width: 190px;
    height: auto;
    margin-top: 5px;
    margin-left: 10px;
}

.doc_manage_span .search_item_fix_width {
    width: 370px;
    height: auto;
    margin-top: 5px;
    margin-left: 10px;
}

.doc_manage_span .search_item_input_width {
    width: 200px;
    height: auto;
    margin-top: 5px;
    margin-left: 10px;
}
.doc_create_dialog > .el-dialog__body{
    padding: 0px;
}
.qr_span{
    display: flex;
    width: 100%;
    height: auto;
    justify-content: center;
}
</style>